package com.aloneness.dingtalk.learn.controller;

import com.aloneness.dingtalk.learn.constant.URLConstant;
import com.aloneness.dingtalk.learn.domain.ResponseBean;
import com.aloneness.dingtalk.learn.domain.DingTalkUser;
import com.aloneness.dingtalk.learn.utils.AccessTokenUtil;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiUserGetRequest;
import com.dingtalk.api.request.OapiUserGetuserinfoRequest;
import com.dingtalk.api.response.OapiUserGetResponse;
import com.dingtalk.api.response.OapiUserGetuserinfoResponse;
import com.taobao.api.ApiException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RestController
@Slf4j
public class LoginController {

    /**
     * 欢迎页面,通过url访问，判断后端服务是否启动
     */
    @RequestMapping(value = "/welcome", method = RequestMethod.GET)
    public String welcome() {
        return "welcome";
    }

    /**
     * 钉钉用户登录，显示当前登录用户的userId和名称
     *
     * @param requestAuthCode 免登临时code
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public ResponseBean login(@RequestParam(value = "authCode") String requestAuthCode, HttpServletRequest httpServletRequest) {
        //获取accessToken,注意正是代码要有异常流处理
        String accessToken = AccessTokenUtil.getToken();

        //获取用户信息
        DingTalkClient client = new DefaultDingTalkClient(URLConstant.URL_GET_USER_INFO);
        OapiUserGetuserinfoRequest request = new OapiUserGetuserinfoRequest();
        request.setCode(requestAuthCode);
        request.setHttpMethod("GET");

        OapiUserGetuserinfoResponse response;
        try {
            response = client.execute(request, accessToken);
        } catch (ApiException e) {
            e.printStackTrace();
            return null;
        }
        // 3.查询得到当前用户的userId
        // 获得到userId之后应用应该处理应用自身的登录会话管理（session）,避免后续的业务交互（前端到应用服务端）每次都要重新获取用户身份，提升用户体验
        String userId = response.getUserid();

        OapiUserGetResponse userProfile = getUserProfile(accessToken, userId);
        String userName = userProfile.getName();
        Long deptId = userProfile.getDepartment().get(0);
        // TODO 审批里的部门id，1和-1要互相转换一下
        if (deptId.longValue() == 1L) {
            deptId = -1L;
        }
        //返回结果
        DingTalkUser user = new DingTalkUser();
        user.setUserId(userId);
        user.setUserName(userName);
        user.setDeptId(deptId);

        // 将user信息保存到session中
        HttpSession session = httpServletRequest.getSession();
        session.setAttribute("userInfo", user);

        ResponseBean responseBean = ResponseBean.success(user);
        return responseBean;
    }

    /**
     * 获取用户详情
     *
     * @param accessToken
     * @param userId
     * @return
     */
    private OapiUserGetResponse getUserProfile(String accessToken, String userId) {
        try {
            DingTalkClient client = new DefaultDingTalkClient(URLConstant.URL_USER_GET);
            OapiUserGetRequest request = new OapiUserGetRequest();
            request.setUserid(userId);
            request.setHttpMethod("GET");
            OapiUserGetResponse response = client.execute(request, accessToken);

            return response;
        } catch (ApiException e) {
            e.printStackTrace();
            return null;
        }
    }
}
